package com.cg.business;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cg.client.CGClient;
import com.cg.client.Point;
import com.cg.client.Prospect;
import com.cg.client.Rides;
import com.cg.client.UsersInRadius;
import com.cg.util.Geohash;






public class CGUserController {
	private static Log log = LogFactory.getLog(CGUserController.class.getName());
	
	public List<Rides> getMatchingCGJourneys(double startAddressGPSlat,
			double startAddressGPSlng,  int startRadius, double endAddressGPSlat,
			double endtAddressGPSlng, int endRadius,Date startTime, Date endTime,String[] temp)throws Exception{
			List<Rides> responseRideList = new ArrayList<Rides>();
			Rides newRide;
			CGClient cgClient = new CGClient();
			UsersInRadius uir=null;
			try{
				uir = cgClient.getUsersInRadius(startAddressGPSlat,
				startAddressGPSlng, startRadius,endAddressGPSlat,
				endtAddressGPSlng, endRadius,  startTime,  endTime);
				if(uir!=null){
					for(Prospect pr : uir.getProspects()){
									
						newRide = prospectToRides(pr,temp);
						responseRideList.add(newRide);
				    }
			
		        }		
		  }catch (Exception e) {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			e.printStackTrace(new PrintStream(out,true));
			log.error(out.toString().replaceAll("\t", " "));
		  }
			return responseRideList;
		
	}
//Converts the Prospect object to a Rides object
private Rides prospectToRides(Prospect pr,String[] temp){
	Rides ride = new Rides();
	Geohash geoHash = new Geohash();
	double[] latlng;
	
	
	
	
	
	List<com.cg.client.Segment> segments = pr.getSegments();

	List<String> transportList = new ArrayList<String>();
		for(int i = 0;i< temp.length; i++){
			transportList.add(temp[i]);
			
		}
		
		
		for(int j=0;j<segments.size();j++){
			String str1 = (String) segments.get(j).getCategory();
				for(int k=0;k<transportList.size();k++){
					String str2 = (String) transportList.get(k);
					if (str2.equalsIgnoreCase(str1)){
						
						log.debug("Matching Journey ID"+pr.getJid());
						log.debug("Matching transport modes :"+str1);
						
						ride.setCategory(segments.get(j).getCategory());
						
						List<Point> pointsMatching = segments.get(j).getPoints();
						log.debug("Matching transfer points :"+pointsMatching.get(0).getGeo());
						
						latlng = geoHash.decode(pointsMatching.get(0).getGeo());
						ride.setStartAddressGpslat(latlng[0]);
						ride.setStartAddressGpslng(latlng[1]);
						
						ride.setId(pr.getJid());
						latlng = geoHash.decode(pr.getGeoEnd());
						
						ride.setEndAddressGpslat(latlng[0]);
						ride.setEndAddressGpslng(latlng[1]);	
						
						ride.setStartTime(com.cg.util.DataUtil.convertDate(pr.getTimeStart()));		
						ride.setEndTime(com.cg.util.DataUtil.convertDate(pr.getTimeEnd()));		
						  
						
						
						
				    if(str1.equalsIgnoreCase("Car")){
						  ride.setGrammesCO2Car(segments.get(j).getGrammesCO2());
						  ride.setDistanceCar(segments.get(j).getDistance());
					}
				    if(str1.equalsIgnoreCase("Bus")){
				    	ride.setGrammesCO2Bus(segments.get(j).getGrammesCO2());
				    	ride.setDistanceBus(segments.get(j).getDistance());
					}
				    if(str1.equalsIgnoreCase("Bicycle")){
				    	System.out.println("BIC DIST"+segments.get(j).getDistance());
				    	ride.setGrammesCO2Bicycle(segments.get(j).getGrammesCO2());
				    	ride.setDistanceBicycle(segments.get(j).getDistance());
				    }
				    if(str1.equalsIgnoreCase("Walking")){
				    	ride.setGrammesCO2Walking(segments.get(j).getGrammesCO2());
				    	ride.setDistanceWalking(segments.get(j).getDistance());
					}
				    if(str1.equalsIgnoreCase("TRAIN_SUBWAY_METRO")){
				    	ride.setGrammesCO2Train(segments.get(j).getGrammesCO2());
				    	ride.setDistanceTrain(segments.get(j).getDistance());
				    }
				    if(str1.equalsIgnoreCase("Ferry")){
				    	ride.setGrammesCO2Ferry(segments.get(j).getGrammesCO2());
				    	ride.setDistanceFerry(segments.get(j).getDistance());
				    }
				    if(str1.equalsIgnoreCase("Aeroplane")){
				    	ride.setGrammesCO2Aeroplane(segments.get(j).getGrammesCO2());
				    	ride.setDistanceAeroplane(segments.get(j).getDistance());
                    }

				} 
					
					
		    
			}
				
		}
	
		return ride;
}



public List<Rides> getPreviousCGJourneys(double startAddressGPSlat,
		double startAddressGPSlng,  int startRadius, double endAddressGPSlat,
		double endtAddressGPSlng, int endRadius,Date startTime, Date endTime,String[] temp)throws Exception{
		List<Rides> previousJourneyList = new ArrayList<Rides>();
		Rides newRide;
		CGClient cgClient = new CGClient();
		UsersInRadius uir=null;
		try{
			uir = cgClient.getUsersInRadius(startAddressGPSlat,
			startAddressGPSlng, startRadius,endAddressGPSlat,
			endtAddressGPSlng, endRadius,  startTime,  endTime);
			if(uir!=null){
				for(Prospect pr : uir.getProspects()){
								
					newRide = previousProspectToRides(pr,temp);
					previousJourneyList.add(newRide);
			    }
		
	        }		
	  }catch (Exception e) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		e.printStackTrace(new PrintStream(out,true));
		log.error(out.toString().replaceAll("\t", " "));
	  }
		return previousJourneyList;
	
}
private Rides previousProspectToRides(Prospect pr,String[] temp){
	Rides ride = new Rides();
	Geohash geoHash = new Geohash();
	double[] latlng;
	
	
	
	
	
	List<com.cg.client.Segment> segments = pr.getSegments();

	List<String> transportList = new ArrayList<String>();
		for(int i = 0;i< temp.length; i++){
			transportList.add(temp[i]);
			
		}
		
		
		for(int j=0;j<segments.size();j++){
			String str1 = (String) segments.get(j).getCategory();
				for(int k=0;k<transportList.size();k++){
					String str2 = (String) transportList.get(k);
					if (str2.equalsIgnoreCase(str1)){
						
						log.debug("Matching Journey ID"+pr.getJid());
						log.debug("Matching transport modes :"+str1);
						
						ride.setCategory(segments.get(j).getCategory());
						
						List<Point> pointsMatching = segments.get(j).getPoints();
						log.debug("Matching transfer points :"+pointsMatching.get(0).getGeo());
						
						latlng = geoHash.decode(pointsMatching.get(0).getGeo());
						ride.setStartAddressGpslat(latlng[0]);
						ride.setStartAddressGpslng(latlng[1]);
						
						ride.setId(pr.getJid());
						latlng = geoHash.decode(pr.getGeoEnd());
						
						ride.setEndAddressGpslat(latlng[0]);
						ride.setEndAddressGpslng(latlng[1]);	
						
						ride.setStartTime(com.cg.util.DataUtil.convertDate(pr.getTimeStart()));		
						ride.setEndTime(com.cg.util.DataUtil.convertDate(pr.getTimeEnd()));		
						  
						
						
						
				    if(str1.equalsIgnoreCase("Car")){
						  ride.setGrammesCO2Car(segments.get(j).getGrammesCO2());
						  ride.setDistanceCar(segments.get(j).getDistance());
					}
				    if(str1.equalsIgnoreCase("Bus")){
				    	ride.setGrammesCO2Bus(segments.get(j).getGrammesCO2());
				    	ride.setDistanceBus(segments.get(j).getDistance());
					}
				    if(str1.equalsIgnoreCase("Bicycle")){
				    	ride.setGrammesCO2Bicycle(segments.get(j).getGrammesCO2());
				    	ride.setDistanceBicycle(segments.get(j).getDistance());
				    }
				    if(str1.equalsIgnoreCase("Walking")){
				    	ride.setGrammesCO2Walking(segments.get(j).getGrammesCO2());
				    	ride.setDistanceWalking(segments.get(j).getDistance());
					}
				    if(str1.equalsIgnoreCase("TRAIN_SUBWAY_METRO")){
				    	ride.setGrammesCO2Train(segments.get(j).getGrammesCO2());
				    	ride.setDistanceTrain(segments.get(j).getDistance());
				    }
				    if(str1.equalsIgnoreCase("Ferry")){
				    	ride.setGrammesCO2Ferry(segments.get(j).getGrammesCO2());
				    	ride.setDistanceFerry(segments.get(j).getDistance());
				    }
				    if(str1.equalsIgnoreCase("Aeroplane")){
				    	ride.setGrammesCO2Aeroplane(segments.get(j).getGrammesCO2());
				    	ride.setDistanceAeroplane(segments.get(j).getDistance());
                    }

				} 
					
					
		    
			}
				
		}
	
		return ride;
}		
//public void WriteXml(ArrayList<String> latLongList,String realPath) throws  TransformerException, ParserConfigurationException{
//			
//		
//				DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//				DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
//				Document document = documentBuilder.newDocument();
//				Element rootElement = document.createElement("markers"); // creates a element
//				int n = 0;
//				while (latLongList.size()> n+1){
//				
//					Element element1 = document.createElement("marker"); //create another element
//				
//				   
//					element1.setAttribute(new String("lat"), latLongList.get(n));
//					n++;
//					element1.setAttribute(new String("lng"), latLongList.get(n));
//					
//				    rootElement.appendChild(element1); // add element1 under rootElement
//					 n++;	
//					 
//					 element1.setAttribute(new String("name"), latLongList.get(n));
//					 n++;
//			   }
//			
//			    document.appendChild(rootElement); // add the rootElement to the document
//
//			    //realPath = realPath.replace('\\', '/');
//			   
//			    //File file = new File("C:/Location.xml");
//			    //File file = new File("C:/Location.xml");
//			   
//			  //  File file= new File( realPath+"\\finalLocation.xml" );
//			    File file = new File( realPath, "\\finalLocation.xml" ); 
//			 
//			 try{
//			TransformerFactory transformerFactory = TransformerFactory.newInstance();
//
//			Transformer transformer = transformerFactory.newTransformer();
//			DOMSource source = new DOMSource(document);
//          //  StreamResult result = new StreamResult(new File(realPath+xsl+".xml"));
//            StreamResult result = new StreamResult(file);
//            transformer.transform(source, result);
//			}			
//			catch (TransformerConfigurationException e)
//			{
//				e.printStackTrace();
//				
//			}
//			catch (TransformerFactoryConfigurationError e)
//			{
//				e.printStackTrace();
//				
//			}
//			catch (TransformerException e)
//			{
//				e.printStackTrace();
//				
//			}
////			 CGUtilClass utilObj = new CGUtilClass();
////			 utilObj.copyfile(realPath);
//			
//		
//}

//public void WriteXmlComp(ArrayList<String> latLongList,String realPath) throws  TransformerException, ParserConfigurationException{
//	
//
//		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//		DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
//		Document document = documentBuilder.newDocument();
//		Element rootElement = document.createElement("markers"); // creates a element
//		int n = 0;
//		while (latLongList.size()> n+1){
//		
//			Element element1 = document.createElement("marker"); //create another element
//		
//		   
//			element1.setAttribute(new String("lat"), latLongList.get(n));
//			n++;
//			element1.setAttribute(new String("lng"), latLongList.get(n));
//			
//		    rootElement.appendChild(element1); // add element1 under rootElement
//			 n++;	
//			 
//			 element1.setAttribute(new String("name"), latLongList.get(n));
//			 n++;
//	   }
//	
//	    document.appendChild(rootElement); // add the rootElement to the document
//
//	    //realPath = realPath.replace('\\', '/');
//	   
//	    //File file = new File("C:/Location.xml");
//	    //File file = new File("C:/Location.xml");
//	   
//	  //  File file= new File( realPath+"\\finalLocation.xml" );
//	    File file = new File( realPath, "\\compareLocation.xml" ); 
//	 
//	 try{
//	TransformerFactory transformerFactory = TransformerFactory.newInstance();
//
//	Transformer transformer = transformerFactory.newTransformer();
//	DOMSource source = new DOMSource(document);
//  //  StreamResult result = new StreamResult(new File(realPath+xsl+".xml"));
//    StreamResult result = new StreamResult(file);
//    transformer.transform(source, result);
//	}			
//	catch (TransformerConfigurationException e)
//	{
//		e.printStackTrace();
//		
//	}
//	catch (TransformerFactoryConfigurationError e)
//	{
//		e.printStackTrace();
//		
//	}
//	catch (TransformerException e)
//	{
//		e.printStackTrace();
//		
//	}
//
//	 //copyfile(realPath);
//	
//
//}
//
}
			